package controller;

import model.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import model.User;
import service.UserService;
import service.UserServiceImpl;
import service.UserServiceImpl;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/home")
public class UserServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String searchKeyword = request.getParameter("searchKeyword");
        int pageIndex = 1; // 默认第一页
        int pageSize = 5; // 默认每页5条记录

        String pageIndexStr = request.getParameter("pageIndex");
        String pageSizeStr = request.getParameter("pageSize");

        if (pageIndexStr != null && !pageIndexStr.isEmpty()) {
            pageIndex = Integer.parseInt(pageIndexStr);
        }
        if (pageSizeStr != null && !pageSizeStr.isEmpty()) {
            pageSize = Integer.parseInt(pageSizeStr);
        }

        try {
            ArrayList<User> users;
            int totalRecords;

            if (searchKeyword != null && !searchKeyword.isEmpty()) {
                // 执行搜索，并获取搜索结果和记录总数
                users = userService.searchUser(searchKeyword, pageIndex, pageSize);
                totalRecords = userService.countSearchUser(searchKeyword);
            } else {
                // 获取所有用户和记录总数
                users = userService.getAllUser(pageIndex, pageSize);
                totalRecords = userService.getUserCount();
            }

            int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
            request.setAttribute("users", users);
            request.setAttribute("totalPages", totalPages);
            request.setAttribute("pageIndex", pageIndex);
            request.setAttribute("searchKeyword", searchKeyword); // 将搜索关键字设置到request中，以便在页面上显示
            int firstItemIndex = (pageIndex - 1) * pageSize + 1;
            request.setAttribute("firstItemIndex", firstItemIndex); // 设置当前页第一个条目的索引

            request.getRequestDispatcher("/home.jsp").forward(request, response);
        } catch (SQLException e) {
            // Handle exception
        }
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}


